<?php

namespace App\Http\Controllers\Admin\ExportContract;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use QrCode;

class ExportContractNanChongHengTongController extends Controller
{

    public function export(Request $request)
    {
        // sleep (5);
        $contract_id = $request->id;
        $data_gaiyao = DB::table('a_contract_gaiyao')->where('contract_id', $contract_id)->orderBy('id', 'asc')->get();
        if ($data_gaiyao->isEmpty()) {
            return '内容为空';
        }

        $template_file = './storage/ExcelTemplate/检测委托单.xls'; //考虑到兼容Linux，斜杠用“/”
        if (!file_exists($template_file)) {
            return '模板文件不存在';
        }

        $data_contract = DB::table('a_contract')->find($contract_id);
        $setting = DB::table('setting')->find(1);

        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($template_file); //读取模板文件
        $worksheet = $spreadsheet->getSheet(0); //按索引获取表单，从 0 开始
        $worksheet->getCell('I2')->setValue($setting->report_num_pre . $data_contract->batchNum); //合同编号
        $worksheet->getCell('C4')->setValue($data_contract->entrusted_company); //委托单位
        $worksheet->getCell('C5')->setValue($data_contract->client_addr); //单位地址

        $first_flag = false; //第一次循环的标志
        $rowIndex = 7;
        foreach ($data_gaiyao as $k=> $val) {
            if ($first_flag) {
                # code...
                $worksheet->insertNewRowBefore($rowIndex, 1); //在第10行之前插入1个新行
                $worksheet->mergeCells('B' . $rowIndex . ':C' . $rowIndex); //合并单元格--样品名称
                $worksheet->mergeCells('F' . $rowIndex . ':J' . $rowIndex); //合并单元格--检验标准
            }

            $worksheet->setCellValueByColumnAndRow(1, $rowIndex, $k + 1); //序号
            $worksheet->setCellValueByColumnAndRow(2, $rowIndex, $val->tool_name); //样品名称
            $worksheet->setCellValueByColumnAndRow(4, $rowIndex, $val->voltage); //电压等级+分类
            $worksheet->setCellValueByColumnAndRow(5, $rowIndex, $val->count . $val->unit); //数量+单位
            $worksheet->setCellValueByColumnAndRow(6, $rowIndex, $val->item_names); //检验项目
            //设置行高
            $strlen = strlen($val->item_names);
            if($strlen > 120){
                $height = floor($strlen  / 66) * 20;  //按照每行66个文字计算,计算出行高
                $worksheet->getRowDimension($rowIndex)->setRowHeight($height);
            }
            // break;
            $first_flag = true;
            $rowIndex++;
        }
        $worksheet->getCell('F'.$rowIndex)->setValue($data_contract->money); //检测费用
        $rowIndex += 2;
        $worksheet->getCell('C'.$rowIndex)->setValue($data_contract->client_tel); //联系电话
        $rowIndex += 1;
        $date = date('Y年m月d日',strtotime($data_contract->created_at));
        $worksheet->getCell('C'.$rowIndex)->setValue('    '.$date); //样品接收日期
        // $worksheet->getProtection()->setSheet(true);
        // $worksheet->getProtection()->setPassword('123');

        //----------直接在浏览器下载----start
        $file_name = "检测委托单" . $data_contract->batchNum . ".xls"; //输出的文件名称
        // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');//告诉浏览器输出Excel 07文件
        header('Content-Type: application/vnd.ms-excel'); //告诉浏览器输出Excel 03版本文件
        header('Content-Disposition: attachment;filename=' . urlencode($file_name)); //告诉浏览器输出的文件名称
        header('Cache-Control: max-age=0'); //禁止缓存
        //----------直接在浏览器下载----end


        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        $writer->setPreCalculateFormulas(false); //禁用公式预先计算
        // $writer->save('write.xls');//将Excel文件保存在服务器的磁盘上
        $writer->save('php://output'); //直接在浏览器下载

        /* //未测试通过
        // $writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf');
        $writer->setPreCalculateFormulas(false);//禁用公式预先计算
        $writer->save("05featuredemo.pdf"); */

        //为了防止内存泄露，建议用完手动清理
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
    }
}
